/* vm */
import { GlobalMixinVM } from "@src/mixins/globalMixin"
/* util */
import { getRootWindow } from '@src/util/dom'

type Tab = {
  id: string;
  title: string;
  // 是否允许关闭tab
  close: boolean;
  // tab对应的url
  url: string;
  // 打开该tab的源tab的id
  fromId: string;
}

enum AuthTabUrlEnum {
  /* start callcenter */
  SettingCallcenterView = '/setting/callcenter/view',
  /* end callcenter */
  
  /* start user */
  UserView = '/security/user/view',
  /* end user */
  
  /* start im */
  ImDetail = '/im/imDetail',
   /* end im */
}

const rootWindow = getRootWindow(window)

function getGlobalRootInstance(): GlobalMixinVM {
  return (rootWindow?.getGlobalRootInstance && rootWindow.getGlobalRootInstance()) || {}
}

function getAuthTabMap(): Record<string, any> {
  
  const globalRootInstance = getGlobalRootInstance()
  
  return {
    [AuthTabUrlEnum.UserView]: globalRootInstance.globalIsHaveUserViewDetailAuth
  }
}

function getAuthTabMapKeys(authTabMap: Record<string, any>) {
  return Object.keys(authTabMap)
}

function checkAuthIsOpenTab(tab: Tab) {
  
  try {
    
    const authTabMap = getAuthTabMap()
    const authTabMapKeys = getAuthTabMapKeys(authTabMap)
    
    const isNeedCheckIndex = isNeedCheckAuthOpenTab(tab.url, authTabMapKeys)
    
    if (isNeedCheckIndex < 0) {
      return true
    }
    
    const authTabKey = authTabMapKeys[isNeedCheckIndex]
    const isHaveAuth = authTabMap[authTabKey]
    
    return Boolean(isHaveAuth)
    
  } catch (error) {
    
    console.error(error)
    
    return true
    
  }
}

function isNeedCheckAuthOpenTab(url: string, authTabKeys: string[]) {
  return authTabKeys.findIndex(authTabUrl => url.includes(authTabUrl))
}

export {
  checkAuthIsOpenTab
}

export default {
  checkAuthIsOpenTab
}